package com.shxc.smarttrade.utils;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool;
import com.bumptech.glide.load.resource.bitmap.BitmapTransformation;
import com.bumptech.glide.signature.StringSignature;
import com.shxc.smarttrade.R;

import jp.wasabeef.glide.transformations.BlurTransformation;
import jp.wasabeef.glide.transformations.GrayscaleTransformation;

/**
 * Glide工具类
 */

public class GlideUtils {

    Context mContext;

    public GlideUtils(Context context) {
        mContext = context;
    }

    /**
     * 简单加载
     *
     * @param url       图片路径
     * @param imageView 用于显示的图片控件
     */
    public void showImage(String url, ImageView imageView) {
        Glide.with(mContext)
                .load(url)
                .diskCacheStrategy(DiskCacheStrategy.SOURCE)
                .crossFade()//加载动画
                .into(imageView);
    }

    /**
     * 设置加载中以及加载失败图片
     *
     * @param url         图片路径
     * @param placeholder 缓存图片路径R.mipmap.XXX
     * @param error       加载失败图片路径R.mipmap.XXX
     * @param imageView   用于显示的图片控件
     */
    public void showImage(String url, ImageView imageView, int placeholder, int error) {
        Glide.with(mContext)
                .load(url)
                .diskCacheStrategy(DiskCacheStrategy.RESULT)
                .placeholder(placeholder)
                .error(error)
                .crossFade()//加载动画
                .into(imageView);
    }

    /**
     * 加载缩略图 然后在加载全图
     *
     * @param url       图片路径
     * @param imageView 用于显示的图片控件
     */
    public void showThumbnail(String url, ImageView imageView, int placeholder, int error) {
        Glide.with(mContext)
                .load(url)
                .diskCacheStrategy(DiskCacheStrategy.SOURCE)
                .thumbnail(0.1f)
                .placeholder(placeholder)
                .error(error)
                .crossFade()//加载动画
                .into(imageView);
    }

    /**
     * 设置加载尺寸
     *
     * @param url       图片路径
     * @param imageView 用于显示的图片控件
     */
    public void showWithSize(String url, ImageView imageView, int width, int height) {
        Glide.with(mContext)
                .load(url)
                .override(width, height)
                .diskCacheStrategy(DiskCacheStrategy.SOURCE)
                .into(imageView);
    }

    /**
     * 显示gif动态图片
     *
     * @param url       图片路径
     * @param imageView 用于显示的图片控件
     */
    public void showGifAsGif(String url, ImageView imageView) {
        Glide.with(mContext)
                .load(url)
                .asGif()
                .diskCacheStrategy(DiskCacheStrategy.SOURCE)
                .into(imageView);
    }

    /**
     * 显示gif静态图片
     *
     * @param url       图片路径
     * @param imageView 用于显示的图片控件
     */
    public void showGifAsBitmap(String url, ImageView imageView) {
        Glide.with(mContext)
                .load(url)
                .asBitmap()
                .diskCacheStrategy(DiskCacheStrategy.SOURCE)
                .into(imageView);
    }

    /**
     * 显示模糊静态图片
     *
     * @param url       图片路径
     * @param imageView 用于显示的图片控件
     */
    public void showBlur(String url, ImageView imageView) {
        Glide.with(mContext)
                .load(url)
                .bitmapTransform(new BlurTransformation(mContext))
                .diskCacheStrategy(DiskCacheStrategy.SOURCE)
                .into(imageView);
    }

    /**
     * 显示黑白静态图片
     *
     * @param url       图片路径
     * @param imageView 用于显示的图片控件
     */
    public void showGrayscale(String url, ImageView imageView) {
        Glide.with(mContext)
                .load(url)
                .bitmapTransform(new GrayscaleTransformation(mContext))
                .diskCacheStrategy(DiskCacheStrategy.SOURCE)
                .into(imageView);
//        Glide.with(mContext)
//                .load(url)
//                .bitmapTransform(new BlurTransformation(mContext), new GrayscaleTransformation(mContext))
//                .into(imageView);//黑白，模糊
    }

    /**
     * 显示圆形图
     *
     * @param url       图片路径
     * @param imageView 用于显示的图片控件
     */
    public void showCircle(String url, final ImageView imageView) {
        //该方式有效
//        Glide.with(mContext).load(url).asBitmap().centerCrop().into(new BitmapImageViewTarget(imageView) {
//            @Override
//            protected void setResource(Bitmap resource) {
//                RoundedBitmapDrawable circularBitmapDrawable =
//                        RoundedBitmapDrawableFactory.create(mContext.getResources(), resource);
//                circularBitmapDrawable.setCircular(true);
//                imageView.setImageDrawable(circularBitmapDrawable);
//            }
//        });
//        Glide.with(mContext).load(url).transform(new CircleTransform(mContext)).placeholder(R.mipmap.default_head).error(R.mipmap.default_head)
//                .diskCacheStrategy(DiskCacheStrategy.SOURCE).into(imageView);
        Glide.with(mContext).load(url).signature( new StringSignature(System.currentTimeMillis()+"")).transform(new CircleTransform(mContext)).placeholder(R.mipmap.default_head).error(R.mipmap.default_head)
                .diskCacheStrategy(DiskCacheStrategy.SOURCE).into(imageView);
    }

    /**
     * 显示圆角图
     *
     * @param url       图片路径
     * @param imageView 用于显示的图片控件
     * @param size      圆角半径 单位dp
     */
    public void showFillet(String url, ImageView imageView, int size) {
        Glide.with(mContext).load(url).transform(new GlideRoundTransform(mContext, size))
                .diskCacheStrategy(DiskCacheStrategy.SOURCE).into(imageView);
    }

    /**
     * 显示圆角图
     *
     * @param url 图片路径
     * @param imageView 用于显示的图片控件
     * @param size 圆角半径 单位dp
     * @param placeholder 加载中的图片
     * @param error 加载错误的图片
     */
    public void showFillet(String url, ImageView imageView, int size, int placeholder, int error) {
        Glide.with(mContext).load(url).transform(new GlideRoundTransform(mContext, size))
                .placeholder(placeholder).error(error)
                .diskCacheStrategy(DiskCacheStrategy.SOURCE).into(imageView);
    }

    //清理磁盘缓存 需要在子线程中执行
    public void clearDiskCache() {
        Glide.get(mContext).clearDiskCache();
    }

    //清理内存缓存  可以在UI主线程中进行
    public void clearMemory() {
        Glide.get(mContext).clearMemory();
    }


    public static class GlideRoundTransform extends BitmapTransformation {

        private float radius = 0f;

        public GlideRoundTransform(Context context) {
            this(context, 4);
        }

        public GlideRoundTransform(Context context, int dp) {
            super(context);
            this.radius = Resources.getSystem().getDisplayMetrics().density * dp;
        }

        @Override
        protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
            return roundCrop(pool, toTransform);
        }

        private Bitmap roundCrop(BitmapPool pool, Bitmap source) {
            if (source == null) return null;

            Bitmap result = pool.get(source.getWidth(), source.getHeight(), Bitmap.Config.ARGB_8888);
            if (result == null) {
                result = Bitmap.createBitmap(source.getWidth(), source.getHeight(), Bitmap.Config.ARGB_8888);
            }

            Canvas canvas = new Canvas(result);
            Paint paint = new Paint();
            paint.setShader(new BitmapShader(source, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP));
            paint.setAntiAlias(true);
            RectF rectF = new RectF(0f, 0f, source.getWidth(), source.getHeight());
            canvas.drawRoundRect(rectF, radius, radius, paint);
            return result;
        }

        @Override
        public String getId() {
            return getClass().getName() + Math.round(radius);
        }
    }

    public static class CircleTransform extends BitmapTransformation {
        public CircleTransform(Context context) {
            super(context);
        }

        @Override
        protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
            return circleCrop(pool, toTransform);
        }

        private static Bitmap circleCrop(BitmapPool pool, Bitmap source) {
            if (source == null) return null;

            int size = Math.min(source.getWidth(), source.getHeight());
            int x = (source.getWidth() - size) / 2;
            int y = (source.getHeight() - size) / 2;

            // TODO this could be acquired from the pool too
            Bitmap squared = Bitmap.createBitmap(source, x, y, size, size);

            Bitmap result = pool.get(size, size, Bitmap.Config.ARGB_8888);
            if (result == null) {
                result = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
            }

            Canvas canvas = new Canvas(result);
            Paint paint = new Paint();
            paint.setShader(new BitmapShader(squared, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP));
            paint.setAntiAlias(true);
            float r = size / 2f;
            canvas.drawCircle(r, r, r, paint);
            return result;
        }

        @Override
        public String getId() {
            return getClass().getName();
        }
    }
}
